from MediaInfoDLL import *


def msToFrames2(ms):
	f = 1000.0 / ( 30000.0 / 1001.0 )
	return int(round( ms / f ))


def msToFrames(ms):
##
# Return #frames from duration in ms
##
	return ms * 3000 / 100000


def _smpte_drop_string_tc(hs, min, seg, frames):

	if hs == 0 or hs < 10:
                hs  = '0' + str(hs)
        else:
                hs = str(hs)

        if min == 0 or min < 10:
                min = '0' + str(min)
        else:
                min = str(min)

        if seg == 0 or seg < 10:
                seg = '0' + str(seg)
        else:
                seg = str(seg)

        if frames == 0 or frames < 10:
                frames = '0' + str(frames)
        else:
                frames = str(frames)

        return hs + ':' + min + ':' + seg + ';' + frames



def _smpte_drop_525i(frames):
	
	print "Frames" + frames

	hour = frames / 107892
    	frames -= hour * 107892

    	min = (frames / 17982) * 10
    	frames -= (min / 10) * 17982 + 2

    	min += (frames / 1798)
    	frames -= (min % 10) * 1798 - 2

    	sec = int(round(frames / 29.97))
    	frames -= int(round(sec * 29.97))  

    	return _smpte_drop_string_tc(hour, min, sec, frames)


def GetStartTC(file = None):
	if file != None:
		if (os.path.isfile(file)):
			try:
				MI = MediaInfo()
				MI.Open(file)
				ms = MI.Get(Stream.Video, 0, u"Delay")
				print ms
				MI.Close()
				return _smpte_drop_525i(msToFrames2(ms))
			except:
				return None
		else:
			return None

	return None	


def GetMediaDuration(filename):
        if os.path.isfile(filename):
                MI = MediaInfo()
                MI.Open(filename)
                format = MI.Get(Stream.General, 0, u"Format")
                if (format == "Wave"):
                        stream = Stream.Audio
                else:
                        stream = Stream.Video
                ms = MI.Get(stream, 0, u"Duration")
                MI.Close()
                return ms



def msToString(ms):
        hours, ms = divmod(int(ms), 3600000)
        minutes, ms = divmod(int(ms), 60000)
        seconds = float(int(ms)) / 1000
        s = "%i:%02i:%06.3f" % (hours, minutes, seconds)
        return s

	
	
	
	



